import 'dart:convert';
import 'dart:io';

import 'package:flutter_chip/bean/ChatMsg.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/GlobalEvent.dart';
import 'package:flutter_chip/utils/sp_utils.dart';

class WebSocketUtils {
  WebSocketUtils._();

  static WebSocketUtils _manager;
  static bool _isSuccess = false;

  factory WebSocketUtils() {
    if (_manager == null) {
      _manager = WebSocketUtils._();
    }
    return _manager;
  }

  WebSocket _webSocket;

  void initWebSocket() async {
    String userStr = await SpUtils.get(SpUtils.SP_USER, "");
    if ("" != userStr) {
      User user = User.fromJson(json.decode(userStr));
      String path = Api.URL_WEB.replaceAll("http", "ws") + "/${user.userId}";
      print("websocket url=$path");
      Future<WebSocket> future = WebSocket.connect(path);
      future.then((webSocket) {
        _webSocket = webSocket;
        webSocket.listen((data) {
          print("收到服务端数据：$data");
          if (data == "连接成功") {
            _isSuccess = true;
            return;
          }
          ChatMsg chatMsg = ChatMsg.fromJson(json.decode(data));
          GlobalEvent().eventBus.fire(chatMsg);
        }, onError: (error) {
          print("服务端onError:$error");
        }, onDone: () {
          print("服务端：onDone");
          _isSuccess = false;
          _webSocket = null;
        });
      });
    }
  }

  void sendMessage(String data, String sendTo) {
    Map<String, String> param = Map();
    param["data"] = data;
    param["sendTo"] = sendTo;
    if (!_isSuccess || null == _webSocket) {
      print("重连webSocket");
      initWebSocket();
      return;
    }
    print("发送数据:$param");
    _webSocket.add(json.encode(param));
  }
}
